package fr.generali.accueilclient.gwt.client.privilege;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Contexte permettant de stocker les ressources auquelles a accès l'utilisateur
 * actuellement connecté.
 */
public class ResourceAccessHolder {

    private static Map<String, GrantedResource> contextHolder;

    public static boolean hasAccess(String resourceName) {
        assertContextHasBeenFetched();
        if (resourceName == null || resourceName.isEmpty()) {
            return true;
        }
        return contextHolder.containsKey(resourceName.trim());
    }

    public static boolean hasAccess(String[] resourceName) {
        assertContextHasBeenFetched();
        if (resourceName != null) {
            for (String element : resourceName) {
                if (hasAccess(element)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static void assertContextHasBeenFetched() {
        if (contextHolder == null) {
            throw new IllegalStateException(
                            "You are trying to check access before the GrantedResources have been fetched from the server");
        }
    }

    public static <T extends GrantedResource> void setGrantedRessources(ArrayList<T> ressources) {
        contextHolder = new HashMap<String, GrantedResource>();
        for (GrantedResource resource : ressources) {
            contextHolder.put(resource.getKey().trim(), resource);
        }
    }
}
